package com.xjh.t.controller;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONConverter;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjh.t.common.DataGridView;
import com.xjh.t.common.ResultObj;
import com.xjh.t.common.WebUtils;
import com.xjh.t.domain.*;
import com.xjh.t.service.*;
import com.xjh.t.vo.OrderGoodsVo;
import com.xjh.t.vo.OrderVo;
import com.xjh.t.vo.UserCartOrderVo;
import com.xjh.t.vo.UserCartVo;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author satela
 * @since 2025-11-09
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IUserCartService userCartService;

    @Autowired
    private IOrderGoodsService orderGoodsService;

    @Autowired
    private IClientUserService clientUserService;

    @Autowired
    private ISalerService salerService;

    @RequestMapping("getUserOrderList")
    public DataGridView getUserOrderList(OrderVo order) {

       // HttpSession session = WebUtils.getSession();
       // ClientUser user =(ClientUser) session.getAttribute("user");

        IPage<Order> page = new Page<>(order.getPage(), order.getLimit());

        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        if(StringUtils.isNotBlank(order.getUserPhone())) {

            QueryWrapper<ClientUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.like(order.getUserPhone() != null, "user_phone", order.getUserPhone());
            List<ClientUser> clientUsers = clientUserService.list(userQueryWrapper);

            if(clientUsers.size() > 0)
            {
                List<Integer> userids = new ArrayList<>();
                for(ClientUser clientUser:clientUsers)
                    userids.add(clientUser.getId());
                orderQueryWrapper.in("user_id",userids);
            }

        }

        orderQueryWrapper.eq(order.getOrderState()!= null && order.getOrderState() < 4,"order_state",order.getOrderState());

        orderQueryWrapper.ge(order.getStartTime() != null, "create_time", order.getStartTime());
        orderQueryWrapper.le(order.getEndTime() != null, "create_time", order.getEndTime());


        orderQueryWrapper.orderByDesc("create_time");

        this.orderService.page(page, orderQueryWrapper);
        List<Order> orderList = page.getRecords();

        List<OrderVo> orderVoList = new ArrayList<>();
        for(Order order1:orderList)
        {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order1,orderVo);

            ClientUser clientUser = clientUserService.getById(order1.getUserId());
            if(clientUser != null) {

                orderVo.setUserName(clientUser.getUrName());
                orderVo.setUserPhone(clientUser.getUrPhone());
                orderVoList.add(orderVo);
            }
        }

        List<Order> orderInfos = this.orderService.list(orderQueryWrapper);
        //sqlsession.close();

        BigDecimal amount = new BigDecimal(0);

        for(Order orderInfo:orderInfos)
        {
            try {
                amount = amount.add(orderInfo.getOrderAmount());
            }
            catch (Exception e)
            {
                //System.out.println(orderInfo.getOrId());
            }
        }


        return new DataGridView(page.getTotal(),orderVoList,amount);
    }


    @RequestMapping("getUserOrderDetail")
    public DataGridView getUserOrderList(Integer orderId) {

       Order order = orderService.getById(orderId);
       if(order !=null) {


           JSONArray arr = new JSONArray(order.getOrderDetail());
           List<Integer> goodsIds = new ArrayList<>();
           for(Object id:arr)
           {
               goodsIds.add((Integer) id);
           }

           QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
           orderGoodsQueryWrapper.in("id",goodsIds);
           List<OrderGoods> orderGoodsList = orderGoodsService.list(orderGoodsQueryWrapper);
           List<OrderGoodsVo> orderGoodsVos = new ArrayList<>();
           for(OrderGoods orderGoods1:orderGoodsList)
           {
               OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
               BeanUtils.copyProperties(orderGoods1,orderGoodsVo);
               Saler saler = salerService.getById(orderGoods1.getBelongSaler());
               if(saler != null)
                   orderGoodsVo.setSalerName(saler.getSalerName());
               Goods goods = goodsService.getById(orderGoods1.getGoodsId());
               orderGoodsVo.setGoodsImg(goods.getGoodsImg());
               orderGoodsVos.add(orderGoodsVo);
           }

           return new DataGridView(orderGoodsVos.size(),orderGoodsVos);

       }
       else
           return new DataGridView(0,new ArrayList<>());

    }

    @Transactional
    @RequestMapping("confirmOrder")
    public Object confirmOrder(@RequestBody ArrayList<UserCartOrderVo> userCartOrderVoList) {

        HttpSession session = WebUtils.getSession();
        ClientUser user =(ClientUser) session.getAttribute("user");

        for(UserCartOrderVo userCartOrderVo:userCartOrderVoList)
        {
            UserCart userCart = userCartService.getById(userCartOrderVo.getCartId());
            if(userCart != null && userCart.getUserId().equals(user.getId())) {

                Goods goods = goodsService.getById(userCart.getGoodsId());
                if(goods == null || goods.getSellOff() == 1 )
                {
                    return ResultObj.GOODS_NON_EXIST;
                }
                if(goods.getSellPrice().compareTo(userCartOrderVo.getGoodsPrice()) != 0)
                {
                    return ResultObj.GOODS_PRICE_ERROR;

                }

                if(userCartOrderVo.getGoodsCount() > goods.getMaxCount())
                {
                    return ResultObj.GOODS_EXCEED_MAX_COUNT;
                }

            }
            else
            {
                return ResultObj.CONFIRM_ORDER_FAILED;
            }
        }

        UUID uuid = UUID.randomUUID();
        Order order = new Order();
        order.setUserId(user.getId());
        order.setCreateTime(new Date());
        order.setDeliveryType(0);
        order.setOrderState(0);
        order.setOverTime(0);
        order.setOrderId(uuid.toString().replace("-", ""));
        orderService.save(order);

        List<Integer> ordergoodsIdList = new ArrayList<>();
        BigDecimal toatlprice = new BigDecimal(0);
        for(UserCartOrderVo userCartOrderVo:userCartOrderVoList)
        {
            UserCart userCart = userCartService.getById(userCartOrderVo.getCartId());
            Goods goods = goodsService.getById(userCart.getGoodsId());
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setBelongOrderId(order.getOrderId());
            orderGoods.setBelongSaler(goods.getBelongSaler());
            orderGoods.setGoodsCount(userCart.getGoodsCount());
            orderGoods.setConfirmTime(order.getCreateTime());
            orderGoods.setGoodsId(userCart.getGoodsId());
            orderGoods.setUserId(userCart.getUserId());
            orderGoods.setGoodsName(goods.getGoodsName());
            orderGoods.setSalerPrice(goods.getSalerPrice());
            orderGoods.setSellPrice(goods.getSellPrice());
            orderGoods.setSellWeight(goods.getUnitAmount());
            orderGoods.setOffWeight(goods.getOffWeight());
            orderGoods.setState(0);

            orderGoodsService.save(orderGoods);

            goods.setSellCount(goods.getSellCount() + userCartOrderVo.getGoodsCount());

            goodsService.updateById(goods);

            ordergoodsIdList.add(orderGoods.getId());
            BigDecimal price = goods.getSellPrice().multiply(new BigDecimal(userCart.getGoodsCount()));
            toatlprice = toatlprice.add(price);

            userCartService.removeById(userCart.getId());
        }

        order.setOrderDetail(ordergoodsIdList.toString());
        order.setOrderAmount(toatlprice);
        orderService.updateById(order);
        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();

        jsonObject.put("code",200);
        data.put("money",toatlprice);
        data.put("orderId",order.getOrderId());

        jsonObject.put("data",data);

        jsonObject.put("msg","确认订单成功");
        return jsonObject;



    }

    @Transactional
    @RequestMapping("confirmPay")
    public ResultObj confirmPay(Integer orderId,Integer state) {

        Order order1 = orderService.getById(orderId);
        if(order1 != null) {

            if(order1.getOrderState() == 2)
                return ResultObj.ORDER_HAS_CANCELED;
            Date curtime = new Date();
            Long diff = curtime.getTime() - order1.getCreateTime().getTime();

            if(diff/1000 > 36000)
            {
                return ResultObj.CONFIRM_PAY_OVERTIME;
            }
            order1.setOrderState(state);
            orderService.updateById(order1);

            JSONArray arr = new JSONArray(order1.getOrderDetail());
            List<Integer> goodsIds = new ArrayList<>();
            for(Object id:arr)
            {
                goodsIds.add((Integer) id);
            }

            QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
            orderGoodsQueryWrapper.in("id",goodsIds);
            List<OrderGoods> orderGoods = orderGoodsService.list(orderGoodsQueryWrapper);
            for(OrderGoods orderGoods1:orderGoods)
                orderGoods1.setHasPay(state);
            orderGoodsService.updateBatchById(orderGoods);

            return ResultObj.UPDATE_SUCESS;

        }
        else
            return ResultObj.CONFIRM_ORDER_FAILED;


    }


    @RequestMapping("getClientUserOrderList")
    public DataGridView getClientUserOrderList(@RequestBody OrderVo orderVoReq) {

         HttpSession session = WebUtils.getSession();
         ClientUser user =(ClientUser) session.getAttribute("user");


        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();


        orderQueryWrapper.eq(orderVoReq.getOrderState() != null,"order_state",orderVoReq.getOrderState());

        orderQueryWrapper.eq("over_time",0);

        orderQueryWrapper.eq("user_id",user.getId());

        Calendar calendar = Calendar.getInstance();
        // 获取当前日期并减去一个月
        calendar.add(Calendar.MONTH, -1);
        Date dateOneMonthAgo = calendar.getTime();

        orderQueryWrapper.ge("create_time", dateOneMonthAgo);
        orderQueryWrapper.le("create_time", new Date());


        orderQueryWrapper.orderByDesc("create_time");

        List<Order> orderList = orderService.list(orderQueryWrapper);

        List<OrderVo> orderVoList = new ArrayList<>();
        for(Order order1:orderList)
        {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order1,orderVo);


            JSONArray arr = new JSONArray(order1.getOrderDetail());
            List<Integer> goodsIds = new ArrayList<>();
            for(Object id:arr)
            {
                goodsIds.add((Integer) id);
            }

            QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
            orderGoodsQueryWrapper.in("id",goodsIds);
            List<OrderGoods> orderGoodsList = orderGoodsService.list(orderGoodsQueryWrapper);
            List<OrderGoodsVo> orderGoodsVos = new ArrayList<>();
            for(OrderGoods orderGoods1:orderGoodsList)
            {
                OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
                BeanUtils.copyProperties(orderGoods1,orderGoodsVo);
                Saler saler = salerService.getById(orderGoods1.getBelongSaler());
                if(saler != null)
                    orderGoodsVo.setSalerName(saler.getSalerName());
                Goods goods = goodsService.getById(orderGoods1.getGoodsId());
                orderGoodsVo.setGoodsImg(goods.getGoodsImg());
                orderGoodsVos.add(orderGoodsVo);
            }

            orderVo.setOrderGoodsVoList(orderGoodsVos);
            orderVoList.add(orderVo);

        }




        return new DataGridView(orderVoList.size(),orderVoList);
    }
    @RequestMapping("cancelOrder")
    public ResultObj cancelOrder(Integer orderId) {

        Order order1 = orderService.getById(orderId);
        if(order1 != null) {

            order1.setOrderState(2);
            orderService.updateById(order1);
            return ResultObj.UPDATE_SUCESS;
        }
        else
            return ResultObj.ORDER_NON_EXIST;
    }
}

